package b2datastructure.graph;

import lombok.Data;

/**
 * @date 2022/2/28 16:55
 */
@Data
public class BinaryTreeNode {
    private Integer id;//唯一码
    private BinaryTreeNode parent;//父节点
    private BinaryTreeNode left;//左子节点
    private BinaryTreeNode right;//右子节点
    private int height;//高度
    private int leftOrRight;//0 表示left 1 表示 right

    public BinaryTreeNode(Integer id, BinaryTreeNode parent, BinaryTreeNode left, BinaryTreeNode right, int height, int leftOrRight) {
        this.id = id;
        this.parent = parent;
        this.left = left;
        this.right = right;
        this.height = height;
        this.leftOrRight = leftOrRight;
    }

    //获取节点的平衡因子
    public int getBalanceFactor(BinaryTreeNode node){
        return node.getLeft().getHeight()-node.getRight().getHeight();
    }
    //判断节点是否平衡
    public boolean isBalanced(BinaryTreeNode node){
        int balanceFactor=Math.abs(getBalanceFactor(node));
        return balanceFactor>1?false:true;
    }
    //LL调整（右旋）
    public void rightRotate(BinaryTreeNode node){
        BinaryTreeNode left=node.getLeft();
        left.setParent(node.parent);
        BinaryTreeNode leftRight=left.getRight();
        left.setRight(node);
        leftRight.setParent(node);
        node.setLeft(leftRight);
        node.setParent(left);
    }
    //RR调整
    public void leftRotate(BinaryTreeNode node){
        BinaryTreeNode right=node.getRight();
        BinaryTreeNode rightLeft=right.getLeft();
        right.setParent(node.getParent());
        node.setParent(right);
        node.setRight(rightLeft);
        rightLeft.setParent(node);
    }
    //LR调整
    public void LRRotate(BinaryTreeNode node){
        BinaryTreeNode right=node.getRight();
        leftRotate(right);
        rightRotate(node);
    }
    //RL调整
    public void RLRotate(BinaryTreeNode node){
        BinaryTreeNode left=node.getLeft();
        rightRotate(left);
        leftRotate(node);
    }

}
